<template>
	<BasicTable @register="registerTable" :rowSelection="rowSelection">
		<template #tableTitle>
			<a-dropdown v-if="selectedRowKeys.length > 0">
				<template #overlay>
					<a-menu>
						<a-menu-item key="1" @click="batchHandleDelete">
							<Icon icon="ant-design:delete-outlined"></Icon>
							删除
						</a-menu-item>
					</a-menu>
				</template>
				<a-button>批量操作
					<Icon icon="ant-design:down-outlined"></Icon>
				</a-button>
			</a-dropdown>
		</template>

		<template #notice="{ record }"> 
			<a @click="handleMsgNoticeDetail({ noticeId: record.noticeId })" :title="record.noticeCode">
        {{ record.noticeCode }}
      </a>
		</template>
		<template #channel="{ record }"> 
			<a @click="handleChannelDetail(record)" :title="record.channelTypeName">
        {{ record.channelTypeName }}
      </a>
		</template>
		<template #action="{ record }">
			<TableAction :actions="getActions(record)" :dropDownActions="getDropDownAction(record)" />
		</template>
	</BasicTable>
	<DetailDrawer @register="registerDetailDrawer" @success="reload" />
	<MsgNoticeForm @register="registerMsgNoticeForm"/>
	<ConfigChannel @register="registerConfigChannel"/>
</template>
<script lang="ts" setup>
import { unref, onMounted, ref } from 'vue'
import { BasicTable, TableAction } from '/@/components/Table';
import { useModal } from '/@/components/Modal';
import { useDrawer } from '/@/components/Drawer';
import { listMsgPush, getMsgHistory, deleteMsgPush, batchDeleteMsgPush, rePush } from './history.api';
import { columns, searchFormSchema } from './history.data';
import MsgNoticeForm from '../notice/components/MsgNoticeForm.vue';
import ConfigChannel from '../notice/components/ConfigChannel.vue';
import DetailDrawer from './DetailDrawer.vue';
import { useMessage } from "/@/hooks/web/useMessage";
import { useListPage } from '/@/hooks/system/useListPage'
import { Icon } from '/@/components/Icon'
import { useUserStore } from '/@/store/modules/user';
import { listSubTenant } from '/@/api/sys/tenant'
import { getNotice, getNoticeChannel } from '../notice/api'
const tenantId = ref()
const isQueryAllTenant = ref(false)
const { createMessage } = useMessage();
const userStore = useUserStore()
const [registerMsgNoticeForm, { openDrawer: openMsgNoticeForm }] = useDrawer();
const [registerDetailDrawer, { openDrawer: openDetailDrawer }] = useDrawer();
const [registerConfigChannel, { openModal: openConfigChannel }] = useModal();

// 列表页面公共参数、方法
const { prefixCls, tableContext } = useListPage({
	designScope: 'msg-history',
	tableProps: {
		title: '推送记录',
		api: listMsgPush,
		columns: columns,
		alwaysShowTitle: true,
		showTableSetting: false,
		rowSelectionTipType: 'onTableTitle',
		beforeFetch: (params) => {
      params.tenantId = unref(tenantId.value)
      params.isQueryAllTenant = unref(isQueryAllTenant.value)
    },
		actionColumn: {
			width: 130,
			title: '操作',
			dataIndex: 'action',
			fixed: 'right',
			slots: { customRender: 'action' },
		},
		immediate: false,
		bordered: false,
		formConfig: {
			schemas: searchFormSchema,
			fieldMapToTime: [['fieldTime', ['startTime', 'endTime'], 'YYYY-MM-DD HH:mm:ss']],
		},
	}
})

const [registerTable, { reload, getForm }, { rowSelection, selectedRowKeys }] = tableContext;

onMounted(() => {
  const { updateSchema } = getForm()
  if (!userStore.getSelectTenant.isMainTenant) {
    reload()
    return
  }
  updateSchema({
    field: 'tenantId',
    componentProps: ({ formModel, formActionType }) => {
      return {
        optionFilterProp: "label",
        labelField: 'name',
        valueField: 'id',
        showSearch: true,
        api: async () => {
					const list : any[] = []
					const respData = await listSubTenant({})
					list.push({ id: 'all', name: '全部租户' })
					list.push(...respData)
					return list
				},
        onSelect: async (value: any, option: any) => {
          console.log("value", value);
					tenantId.value = value
					isQueryAllTenant.value = false
					if (value === 'all') {
						tenantId.value = userStore.getSelectTenant.mainTenantId
						isQueryAllTenant.value = true
					}
				
          reload()
        },
        onOptionsChange: async (options) => {
          if (options.length > 0) {
            formModel.tenantId = options[0].value
            tenantId.value = options[0].value
            console.log('tenantId', tenantId.value);

						if (options[0].value === 'all') {
							tenantId.value = userStore.getSelectTenant.mainTenantId
							isQueryAllTenant.value = true
						}
            reload()
          }
        }
      }
    },
  })
})

function getActions(record) {
	return [
		{
			label: '推送',
			popConfirm: {
				title: '确定要重新推送?',
				confirm: handleRePush.bind(null, record),
			},
		}
	]
}

const handleMsgNoticeDetail = ({ noticeId }) => {
	openMsgNoticeForm(true, {
		isUpdate: true,
		record: {
			id: noticeId
		}
	}
	)
}

const handleChannelDetail = async (record) => {
	createMessage.loading({
		content: '加载中...',
		key: 'handleChannelDetail'
	})
	let time = setTimeout(async () => {
		try {
			const notice = await getNotice({ id: record.noticeId })
			openConfigChannel(true, {  
				record: notice,
				selectedChannel: {
					code: record.channelType,
					name: record.channelTypeName,
					id: record.channelId,
				}, 
				showEdit: false 
			});

		} finally {
			createMessage.destroy('handleChannelDetail')
			clearTimeout(time)
		}
	}, 200)

}

async function handleDelete(record) {
	await deleteMsgPush({ id: record.id }, reload);
}

/**
 * 重新推送消息
 */
function handleRePush(record) {
	createMessage.loading({
    content: `正在推送消息...`,
    key: 're_push_msg',
    duration: 0,
  });

	rePush({ id: record.id }).then(res => {
		reload()
		createMessage.success({
      content: `推送结束`,
      key: 're_push_msg',
      duration: 2,
    });
		getMsgHistory({ id: record.id, tenantId: record.tenantId }).then(getData => {
			openDetailDrawer(true, { record: getData })
		})
	}).catch(res => {
		createMessage.destroy('re_push_msg');
		reload()
		getMsgHistory({ id: record.id, tenantId: record.tenantId }).then(getData => {
			openDetailDrawer(true, { record: getData })
		})
	})
}

function handleDetail(record) {
	openDetailDrawer(true, { record })
}

async function batchHandleDelete() {
	await batchDeleteMsgPush({ ids: selectedRowKeys.value }, reload);
}

function getDropDownAction(record) {
	return [
		{
			label: '详情',
			onClick: handleDetail.bind(null, record),
		},
		{
			label: '删除',
			popConfirm: {
				title: '是否确认删除',
				confirm: handleDelete.bind(null, record),
			},
		}
	]
}
</script>
